package com.application.chiettinhdienluc.rsclient;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import javax.ws.rs.core.MediaType;

import android.annotation.SuppressLint;
import android.util.Log;
import android.widget.Toast;

import com.application.chiettinhdienluc.app.MainApplication;
import com.application.chiettinhdienluc.data.GlobalData;
import com.application.chiettinhdienluc.model.ChietTinhModel;
import com.application.chiettinhdienluc.model.HinhAnhChiTietModel;
import com.application.chiettinhdienluc.model.NhanCongChiTietModel;
import com.application.chiettinhdienluc.model.VatTuChiTietModel;
import com.google.gson.Gson;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataBodyPart;
import com.sun.jersey.multipart.FormDataMultiPart;


public class NetClientPost {

	private String baseURI;

	public NetClientPost(String uri) {
		baseURI = uri;
	}

	public String submitHoSoKhachHang(ChietTinhModel ct) {

		String output = "";
		try {

			URL url = new URL(baseURI + "/postkhachhang");
			
			Log.i("Submit URL", url.toString());

			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);

			conn.setRequestMethod("POST");

			//conn.setRequestProperty("Content-Type", "application/json");
			conn.setRequestProperty("Content-Type", "application/json"); 
			conn.setRequestProperty("charset", "utf-8");
			
			

			Gson gson = new Gson();
			String input = gson.toJson(ct);
			
			
			
			input = "{\"banctinhId\": null,\"maloaiHs\": \""+ ct.get_MaLoaiHoSo() +
					"\", \"lan\": \"1\", \"maYcauKnai\": \"" +ct.get_MaYeuCauKhieuNai() +
					"\", \"tenKhang\": \""+ ct.get_TenKhachHang()+
					"\", \"diaChi\": \""+ct.get_DiaChi()+
					"\", \"ngayNd\": \""+  ct.get_FormattedNgayND() +
					"\", \"dthoaiDvu\": \"" +ct.get_DienThoaiDichVu() +
					"\",\"bbKsat\": \"" + ct.get_BienBanKhaoSat()+ 
					"\", \"ngayKsat\":\"" +  ct.get_FormattedNgayKhaoSat() +
					"\", \"nvienKs\": \""+ ct.get_NhanVienKhaoSat()  +
					"\", \"ttnha\": \""+ ct.get_ThongTinNha() +
					"\", \"tthd\": \""+ ct.get_ThongTinHopDong() +
					"\", \"maTram\": \""+ ct.get_MaTram() +
					"\", \"tenTram\": \""+ ct.get_TenTram() +
					"\",\"csuatTram\": \""+ ct.get_CongSuatTram() +
					"\", \"maGcst\": \""+ ct.get_MaGCST() +
					"\",\"maGcsp\": \"" + ct.get_MaGCSP() +
					"\", \"ngayCtinh\": \""+  ct.get_FormattedNgayChietTinh() +					
					"\",\"dviDtu\": \""+ ct.get_DonViDauTu() +
					"\",\"trangThai\": \""+ 1 +
					"\",\"thucHien\":\""  + ct.get_ThucHien()   +
					"\",\"maDviqly\": \""+ct.get_MaDonViQuanLy()+"\"}";
			
			String input1 = "{\"banctinhId\": \""+ ct.get_MaBanChietTinh() +
					"\", \"cphiTt\": \""+ new Double(ct.get_ChiPhiTT()).longValue() +
					"\", \"cphiVt\": \""+ new Double(ct.get_ChiPhiVT()).longValue() +
					"\", \"cphiVl\": \"" +new Double(ct.get_ChiPhiVL()).longValue() + 
					"\", \"cphiVc\": \""+ new Double(ct.get_ChiPhiVC()).longValue() +
					"\", \"cphiNc\": \""+ new Double(ct.get_ChiPhiNC()).longValue()  + 
					"\", \"cphiMm\": \"" +new Double(ct.get_ChiPhiMM()).longValue() +
					"\", \"cphiTtk\": \"" + new Double(ct.get_ChiPhiTTK()).longValue() +
					"\",\"cphiC\": \"" +  new Double(ct.get_ChiPhiC()).longValue() + 
					"\", \"cphiTl\":\"" + new Double( ct.get_ChiPhiTL()).longValue()+ 
					"\", \"cphiK\": \""+ new Double(ct.get_ChiPhiK()).longValue() +
					"\", \"tienGtt\": \""+ new Double(ct.get_TienGTT()).longValue() +
					"\", \"tienGtgt\": \""+ new Double(ct.get_TienGTGT()).longValue() +
					"\", \"soTien\": \""+ new Double(ct.get_SoTien()).longValue() + 
					"\", \"lamTron\": \""+ new Double(ct.get_LamTron()).longValue() + 
					"\", \"lan\": \""+ 1 +
					"\",\"trangThai\": \""+ 1 +
					"\",\"thucHien\":\""  + ct.get_ThucHien()   +
					"\",\"maDviqly\": \""+ct.get_MaDonViQuanLy()+"\"}";
			   
			Log.i("Ho So Khach Hang Input", input);
			Log.i("Ho So Chiet Tinh Input", input1);
			
			conn.setRequestProperty("Content-Length", "" + 
		               Integer.toString(input.getBytes().length));

			OutputStream os = conn.getOutputStream();
			os.write(input.getBytes());
			os.flush();

			if (conn.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ conn.getResponseCode());
			}

			// BufferedReader br = new BufferedReader(new
			// InputStreamReader((conn.getInputStream())));

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), "UTF-8"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}

			conn.disconnect();

			output = sb.toString();

		} catch (MalformedURLException e) {

			e.printStackTrace();

		} catch (IOException e) {

			e.printStackTrace();

		}

		return output;

	}
	
	@SuppressLint("UseValueOf")
	public String submitHoSoChietTinh(ChietTinhModel ct) {

		String output = "";
		try {

			URL url = new URL(baseURI + "/postchiettinh");

			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);

			conn.setRequestMethod("POST");

		
			conn.setRequestProperty("Content-Type", "application/json"); 
			conn.setRequestProperty("charset", "utf-8");
			
			

			Gson gson = new Gson();
			String input = gson.toJson(ct);
			
			
			
			input = "{\"banctinhId\": \""+ ct.get_MaBanChietTinh() +
					"\", \"cphiTt\": \""+ new Double(ct.get_ChiPhiTT()).longValue() +
					"\", \"cphiVt\": \""+ new Double(ct.get_ChiPhiVT()).longValue() +
					"\", \"cphiVl\": \"" +new Double(ct.get_ChiPhiVL()).longValue() + 
					"\", \"cphiVc\": \""+ new Double(ct.get_ChiPhiVC()).longValue() +
					"\", \"cphiNc\": \""+ new Double(ct.get_ChiPhiNC()).longValue()  + 
					"\", \"cphiMm\": \"" +new Double(ct.get_ChiPhiMM()).longValue() +
					"\", \"cphiTtk\": \"" + new Double(ct.get_ChiPhiTTK()).longValue() +
					"\",\"cphiC\": \"" +  new Double(ct.get_ChiPhiC()).longValue() + 
					"\", \"cphiTl\":\"" + new Double( ct.get_ChiPhiTL()).longValue()+ 
					"\", \"cphiK\": \""+ new Double(ct.get_ChiPhiK()).longValue() +
					"\", \"tienGtt\": \""+ new Double(ct.get_TienGTT()).longValue() +
					"\", \"tienGtgt\": \""+ new Double(ct.get_TienGTGT()).longValue() +
					"\", \"soTien\": \""+ new Double(ct.get_SoTien()).longValue() + 
					"\", \"lamTron\": \""+ new Double(ct.get_LamTron()).longValue() + 
					"\", \"lan\": \""+ 1 +
					"\",\"trangThai\": \""+ 1 +
					"\",\"thucHien\":\""  + ct.get_ThucHien()   +
					"\",\"maDviqly\": \""+ct.get_MaDonViQuanLy()+"\"}";
			   
			Log.i("Input", input);
			
			conn.setRequestProperty("Content-Length", "" + 
		               Integer.toString(input.getBytes().length));

			OutputStream os = conn.getOutputStream();
			os.write(input.getBytes());
			os.flush();

			if (conn.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ conn.getResponseCode());
			}

			// BufferedReader br = new BufferedReader(new
			// InputStreamReader((conn.getInputStream())));

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), "UTF-8"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}

			conn.disconnect();

			output = sb.toString();

		} catch (MalformedURLException e) {

			e.printStackTrace();

		} catch (IOException e) {

			e.printStackTrace();

		}

		return output;

	}
	
	public String submitChiTietVatTu(List<VatTuChiTietModel> vtctList, String bancttinhid) {

		String output = "";
		try {

			URL url = new URL(baseURI + "/postvattu");

			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);

			conn.setRequestMethod("POST");

			//conn.setRequestProperty("Content-Type", "application/json");
			conn.setRequestProperty("Content-Type", "application/json"); 
			conn.setRequestProperty("charset", "utf-8");
			
			String input;
			
			Log.i("Ban chiet tinh id::::",bancttinhid );
			
			String matusinh = bancttinhid.substring(6);
			
			StringBuilder sb = new StringBuilder();
			sb.append("[");
			
			
			for(int i = 0; i < vtctList.size(); i++) {
				
				vtctList.get(i).setBangChietTinhId(bancttinhid);
				
				vtctList.get(i).setChiTietId(Long.valueOf(matusinh+i));
				
				sb.append(vtctList.get(i).getJsonString()); 
				if(i<vtctList.size()-1) {
					sb.append(",");
				}
				
			}	
			
			sb.append("]");
			
			input = sb.toString();
			
			
			//input = "{\"banctinhId\": null,\"maloaiHs\": \""+ ct.get_MaLoaiHoSo() +"\", \"lan\": \"1\", \"maYcauKnai\": \"" +ct.get_MaYeuCauKhieuNai() + "\", \"tenKhang\": \""+ ct.get_TenKhachHang()+"\", \"diaChi\": \""+ct.get_DiaChi()+"\", \"ngayNd\": "+  "null" +", \"dthoaiDvu\": \"" +ct.get_DienThoaiDichVu() +"\",\"bbKsat\": \"" + ct.get_BienBanKhaoSat()+ "\", \"ngayKsat\":" +  "null" + ", \"nvienKs\": \""+ ct.get_NhanVienKhaoSat() +"\", \"ttnha\": \""+ ct.get_ThongTinNha() +"\", \"tthd\": \""+ ct.get_ThongTinHopDong() +"\", \"maTram\": \""+ ct.get_MaTram() +"\", \"tenTram\": \""+ ct.get_TenTram() +"\",\"csuatTram\": \""+ ct.get_CongSuatTram() +"\", \"maGcst\": \""+ ct.get_MaGCST() +"\",\"maGcsp\": null,\"ngayCtinh\": \""+ ct.get_MaGCSP() +"\",\"dviDtu\": \""+ ct.get_DonViDauTu() +"\",\"trangThai\": null,\"thucHien\": null,\"maDviqly\": \""+ct.get_MaDonViQuanLy()+"\"}";
			   
			Log.i("Input", input);
			conn.setRequestProperty("Content-Length", "" + 
		               Integer.toString(input.getBytes().length));

			OutputStream os = conn.getOutputStream();
			os.write(input.getBytes());
			os.flush();

			if (conn.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ conn.getResponseCode());
			}

			// BufferedReader br = new BufferedReader(new
			// InputStreamReader((conn.getInputStream())));

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), "UTF-8"), 8);
			StringBuilder sb1 = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb1.append(line + "\n");
			}

			conn.disconnect();

			output = sb1.toString();

		} catch (MalformedURLException e) {

			e.printStackTrace();

		} catch (IOException e) {

			e.printStackTrace();

		}

		return output;

	}
	
	
	public String submitChiTietNhanCong(List<NhanCongChiTietModel> ncList, String bancttinhid) {

		String output = "";
		try {

			URL url = new URL(baseURI + "/postnhancong");

			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);

			conn.setRequestMethod("POST");

			//conn.setRequestProperty("Content-Type", "application/json");
			conn.setRequestProperty("Content-Type", "application/json"); 
			conn.setRequestProperty("charset", "utf-8");
			
			String input;
			
			String matusinh = bancttinhid.substring(6);
			
			StringBuilder sb = new StringBuilder();
			sb.append("[");
			
			
			for(int i = 0; i < ncList.size(); i++) {
				
				ncList.get(i).setBangChietTinhId(bancttinhid);
				ncList.get(i).setChiTietId(Long.valueOf(matusinh+i));
				ncList.get(i).setMaDviQly(MainApplication.getMaDonViQuanLy());
				
				sb.append(ncList.get(i).getJsonString()); 
				if(i<ncList.size()-1) {
					sb.append(",");
				}
				
			}	
			
			sb.append("]");
			
			input = sb.toString();
			
			
			//input = "{\"banctinhId\": null,\"maloaiHs\": \""+ ct.get_MaLoaiHoSo() +"\", \"lan\": \"1\", \"maYcauKnai\": \"" +ct.get_MaYeuCauKhieuNai() + "\", \"tenKhang\": \""+ ct.get_TenKhachHang()+"\", \"diaChi\": \""+ct.get_DiaChi()+"\", \"ngayNd\": "+  "null" +", \"dthoaiDvu\": \"" +ct.get_DienThoaiDichVu() +"\",\"bbKsat\": \"" + ct.get_BienBanKhaoSat()+ "\", \"ngayKsat\":" +  "null" + ", \"nvienKs\": \""+ ct.get_NhanVienKhaoSat() +"\", \"ttnha\": \""+ ct.get_ThongTinNha() +"\", \"tthd\": \""+ ct.get_ThongTinHopDong() +"\", \"maTram\": \""+ ct.get_MaTram() +"\", \"tenTram\": \""+ ct.get_TenTram() +"\",\"csuatTram\": \""+ ct.get_CongSuatTram() +"\", \"maGcst\": \""+ ct.get_MaGCST() +"\",\"maGcsp\": null,\"ngayCtinh\": \""+ ct.get_MaGCSP() +"\",\"dviDtu\": \""+ ct.get_DonViDauTu() +"\",\"trangThai\": null,\"thucHien\": null,\"maDviqly\": \""+ct.get_MaDonViQuanLy()+"\"}";
			   
			Log.i("Input", input);
			conn.setRequestProperty("Content-Length", "" + 
		               Integer.toString(input.getBytes().length));

			OutputStream os = conn.getOutputStream();
			os.write(input.getBytes());
			os.flush();

			if (conn.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ conn.getResponseCode());
			}

			// BufferedReader br = new BufferedReader(new
			// InputStreamReader((conn.getInputStream())));

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), "UTF-8"), 8);
			StringBuilder sb1 = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb1.append(line + "\n");
			}

			conn.disconnect();

			output = sb1.toString();

		} catch (MalformedURLException e) {

			e.printStackTrace();

		} catch (IOException e) {

			e.printStackTrace();

		}

		return output;

	}	
	
	
	public String uploadHinhAnhHoSo(String  fileName, String bancttinhid, String banCTServerId) {
		
		String result = "";
		String uploadFilePath = GlobalData.sdcardPath + "/ChietTinh";  		
		Log.i("upload hinh",fileName);
		Log.i("upload hinh File URI ",uploadFilePath);
		
		result = uploadFile(uploadFilePath , fileName, banCTServerId);
		
		return result;
		
	}
	
	public String uploadFile(String uploadFilePath, String fileName, String banCTServerId) {
        
		int serverResponseCode = 0;
		String result = "fail";
		String upLoadServerUri = baseURI + "/uploadimage";
		   
        

        HttpURLConnection conn = null;
        DataOutputStream dos = null;  
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024; 
        File sourceFile = new File(uploadFilePath + "/" + fileName); 
         
        if (!sourceFile.isFile()) {
             
           Log.e("uploadFile", "Source File not exist :" +uploadFilePath + "/" + fileName);
           return result;
          
        }
        else
        {
        	 Log.i("uploadFile", "Source File exist :" + uploadFilePath + "" + fileName);
        	 Log.i("upload Server URI = ", upLoadServerUri);
        	 
             try { 
                  
                   // open a URL connection to the Servlet
                 FileInputStream fileInputStream = new FileInputStream(sourceFile);
                 URL url = new URL(upLoadServerUri);
                  
                 // Open a HTTP  connection to  the URL
                 conn = (HttpURLConnection) url.openConnection(); 
                 conn.setDoInput(true); // Allow Inputs
                 conn.setDoOutput(true); // Allow Outputs
                 conn.setUseCaches(false); // Don't use a Cached Copy
                 conn.setRequestMethod("POST");
                 conn.setRequestProperty("Connection", "Keep-Alive");
                 conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                 conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                 conn.setRequestProperty("file", fileName); 
                 //conn.setRequestProperty("banchiettinhid", banCTServerId); 
                  
                 dos = new DataOutputStream(conn.getOutputStream());
        
                 dos.writeBytes(twoHyphens + boundary + lineEnd); 
                 dos.writeBytes("Content-Disposition: form-data; name=" + "file" + ";filename="
                                           + banCTServerId+ "_" +fileName + "" + lineEnd);
                  
                 dos.writeBytes(lineEnd);
        
                 // create a buffer of  maximum size
                 bytesAvailable = fileInputStream.available(); 
        
                 bufferSize = Math.min(bytesAvailable, maxBufferSize);
                 buffer = new byte[bufferSize];
        
                 // read file and write it into form...
                 bytesRead = fileInputStream.read(buffer, 0, bufferSize);  
                    
                 while (bytesRead > 0) {
                      
                   dos.write(buffer, 0, bufferSize);
                   bytesAvailable = fileInputStream.available();
                   bufferSize = Math.min(bytesAvailable, maxBufferSize);
                   bytesRead = fileInputStream.read(buffer, 0, bufferSize);   
                    
                  }
        
                 // send multipart form data necesssary after file data...
                 dos.writeBytes(lineEnd);
                 dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        
                 // Responses from the server (code and message)
                 serverResponseCode = conn.getResponseCode();
                 String serverResponseMessage = conn.getResponseMessage();
                   
                 Log.i("uploadFile", "HTTP Response is : "
                         + serverResponseMessage + ": " + serverResponseCode);
                  
                 if(serverResponseCode == 200){
                      
                	 Log.i("uploadFile", "Ok");     
                	 result = "success";
                 }    
                  
                 //close the streams //
                 fileInputStream.close();
                 dos.flush();
                 dos.close();
                   
            } catch (MalformedURLException ex) {           
              
                ex.printStackTrace();                
                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
                
            } catch (Exception e) {                 
              
                e.printStackTrace();              
                Log.e("Upload file to server Exception", "Exception : "
                                                 + e.getMessage(), e);  
            }
           
            return result; 
             
         } 
       }
	
	   
}